<?php
namespace app\myadmin\model;
use think\Model;
use think\facade\Session;
use think\facade\Cookie;
use think\Db;
class Login extends Model
{
	// 表名配置
	protected $name = "admin";
	// 时间戳配置
	protected $autoWriteTimestamp = true;
	// 定义时间戳字段名
	protected $createTime = "create_time";
	protected $updateTime = "update_time";
	// 登录
	public function index($Data)
	{
		$Data=TrimArray($Data);
		$validate = new \app\myadmin\validate\Login;
		if (!$validate->check($Data)) {
			return ["code"=>1,"msg"=>$validate->getError()];
		}
		$info=$this->where("username",$Data["username"])->where("password",Getmd5Pass($Data["password"]))->field("id,username,nickname,status,cateId")->find();
		if($info){
			if($info["status"]==2){
				return ["code"=>1,"msg"=>"账号禁用"];
			}
			// 登录成功记录session
			$cate=Db::name("cate")->where("id",$info["cateId"])->where("status",1)->value("permissions");	// 缓存
			$authArr=[];
			if($cate){
				foreach (explode(",",$cate) as $val) {
					$menu=Db::name("menu")->where("id",$val)->field("module,controller,function")->find();
					if($menu["module"]!=""||$menu["controller"]!=""||$menu["function"]!=""){
						$authArr[] = $menu["module"]."/".$menu["controller"]."/".$menu["function"];
					}
				}
			}
			Session::set("authList_".$info["id"],array_unique($authArr));
			Session::set("adminId",$info["id"]);
			Session::set("userName",$info["username"]);
			Session::set("cateId",$info["cateId"]);
			Session::set("nickName", $info["nickname"]);
			if(!empty($Data["remember"])){
				Cookie::set("userName", $info["username"]);		// 登录成功并记住账号记录cookie
			}
			$this->where("id",$info["id"])->update(["loginIp"=>GetIp(),"login_time"=>time()]);
			return ["code"=>0,"msg"=>"正在跳转"];
		}else{
			return ["code"=>1,"msg"=>"操作失败"];
		}
	}
}
